package al.work.common.util;

import com.google.gson.*;
import com.google.gson.internal.bind.ObjectTypeAdapter;
import org.reflections.Reflections;

import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * 处理json解析的工具类
 */
public class GsonUtils {

    private static final Gson gson = initliaze();

    public static Gson initliaze() {
        final GsonBuilder builder = new GsonBuilder();
        final Reflections reflections = new Reflections("com.xc.market");
        builder.setDateFormat("yyyy-MM-dd hh:mm:ss");
        builder.registerTypeAdapter(Date.class,
            (JsonSerializer<Date>) (date, type, jsonSerializationContext) -> {
                if (null == date) {
                    return null;
                }
                return new JsonPrimitive(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date));
            }
        );
        builder.registerTypeAdapter(Date.class,
                new JsonDeserializer<Date>() {
                    @Override
                    public Date deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
                        try {
                            return df.parse(jsonElement.getAsString());
                        } catch (ParseException e) {
                            return null;
                        }
                    }
                    DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                }
        );
        Gson result = builder.create();
        try {
            Field factories = Gson.class.getDeclaredField("factories");
            factories.setAccessible(true);
            Object o = factories.get(result);
            Class<?>[] declaredClasses = Collections.class.getDeclaredClasses();
            for (Class c : declaredClasses) {
                if ("java.util.Collections$UnmodifiableList".equals(c.getName())) {
                    Field listField = c.getDeclaredField("list");
                    listField.setAccessible(true);
                    List<TypeAdapterFactory> list = (List<TypeAdapterFactory>) listField.get(o);
                    int i = list.indexOf(ObjectTypeAdapter.FACTORY);
                    list.set(i, GsonMapTypeAdapter.FACTORY);
                    break;
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return result;
    }

    public static <T> T fromJson(String json, Class<T> classOfT) {
        if (null == json) return null;
        try{
            T t = gson.fromJson(json, classOfT);
            return t;
        } catch (Exception ex) {
            return null;
        }
    }

    public static <T> T fromBytes(byte[] bytes, Class<T> classOfT) {
        if (null == bytes) return null;
        String json = new String(bytes, StandardCharsets.UTF_8);
        return fromJson(json, classOfT);
    }

    public static Object fromJson(String json, Type type) {
        if (null == json) return null;
        try{
            Object t = gson.fromJson(json, type);
            return t;
        } catch (Exception ex) {
            return null;
        }
    }

    public static Object fromBytes(byte[] bytes, Type type) {
        if (null == bytes) return null;
        String json = new String(bytes, StandardCharsets.UTF_8);
        return fromJson(json, type);
    }

    public static String toJson(Object object) {
        return gson.toJson(object);
    }
}
